<template>
  <a-spin :spinning="loading">
    <div class="flex-center-between">
      <div class="flex-center">
        <a-month-picker v-model="date" :allowClear="false" placeholder="选择月份" @change="onMonthChange" style="width: 180px" />
        <a-input-search
          v-model="companyName"
          placeholder="请输入公司名称"
          allowClear
          class="ml16"
          style="width: 180px"
          @change="onNameChange"
        />
        <a-select v-model="customerDetailsType" placeholder="请选择明细表类型" allowClear class="ml16" style="width: 180px">
          <a-select-option value="customer">客户明细表</a-select-option>
          <a-select-option value="salary">薪资明细表</a-select-option>
          <a-select-option value="social">社保明细表</a-select-option>
        </a-select>
      </div>
      <a-button v-if="groupType === 'company'" type="primary" @click="showAdd"><a-icon type="container" />生成明细表</a-button>
      <a-button v-else type="primary" @click="$refs.tabGroup.showAdd"><a-icon type="container" />生成自定义分组</a-button>
    </div>
    <div class="flex-center mv16">
      <div
        class="ta-center fh32 br20 ph24 pointer bgc-white mr16 fw500"
        :class="{ 'bgc-theme': groupType === 'company', 'tc-white': groupType === 'company' }"
        @click="groupType = 'company'"
      >
        客户明细
      </div>
      <div
        class="ta-center fh32 br20 ph24 pointer bgc-white fw500"
        :class="{ 'bgc-theme': groupType === 'customGrouping', 'tc-white': groupType === 'customGrouping' }"
        @click="groupType = 'customGrouping'"
      >
        统计报表
      </div>
    </div>
    <TabGroup ref="tabGroup" v-show="groupType === 'customGrouping'" :date="date" />
    <div v-show="groupType === 'company'">
      <div v-if="groupList && groupList.length">
        <div v-for="(item, index) in groupList" :key="index">
          <div class="bgc-white p24 mt12 br8 flex-center" style="height: 100px">
            <a-tooltip :title="item.name">
              <div class="flex-center flex-shrink-0 border-right" style="width: 200px">
                <div class="noShowIcon" style="cursor: pointer">
                  <a-icon type="file-text" theme="filled" />
                </div>
                <div class="fw500 fs18 ellipsis tc-l1 pr20 flex-1">{{ item.name }}</div>
              </div>
            </a-tooltip>
            <div class="flex-center-between ml24 flex-1">
              <div>
                <div class="ta-center fs12 tc-l2">明细表月份</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ formatYM(item.yearly, item.monthly) }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">明细表类型</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ typeDict[item.customerDetailsType] }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">薪资数据来源月份</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ formatYM(item.salaryYearly, item.salaryMonthly) }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">社保数据来源月份</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ formatYM(item.socialYearly, item.socialMonthly) }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">本月人数</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ item.empNumber }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">创建人</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ item.createUserName }}</div>
              </div>
              <div>
                <div class="ta-center fs12 tc-l2">创建时间</div>
                <div class="ta-center fs14 tc-l3 mt8">{{ $dayjs(item.gmtCreate).format("YYYY-MM-DD") }}</div>
              </div>
              <a-space>
                <span class="pointer tc-theme" @click="goDetail(item)">详情</span>
                <a-popconfirm title="记录删除后将无法恢复，确定要删除吗？" placement="topRight" @confirm="deleteItem(item)">
                  <span
                    v-if="!item.hrMonthlySalarySummaryVOList || item.hrMonthlySalarySummaryVOList.length === 0"
                    class="pointer tc-theme"
                  >
                    删除
                  </span>
                </a-popconfirm>
              </a-space>
            </div>
          </div>
        </div>
        <div class="flex-center-end mt24">
          <a-pagination
            v-model="pagination.current"
            :total="pagination.total"
            :pageSize.sync="pagination.pageSize"
            :showQuickJumper="pagination.showQuickJumper"
            :showSizeChanger="pagination.showSizeChanger"
            :showTotal="pagination.showTotal"
            :size="pagination.size"
            :pageSizeOptions="pagination.pageSizeOptions"
            @change="onShowSizeChange"
            @showSizeChange="onShowSizeChange"
          />
        </div>
      </div>
      <div v-else style="padding: 120px 0px 560px 0px; background-color: #f2f3f5">
        <a-empty />
      </div>
    </div>
    <a-modal v-model="addVisible" title="生成明细表" @ok="handleAddOk" @cancel="onCancel">
      <a-form-model ref="ruleForm" :model="addForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" style="margin-top: 15px">
        <a-form-model-item
          :rules="{
            required: true,
            message: '请选择'
          }"
          ref="date"
          label="明细表月份"
          prop="date"
        >
          <a-month-picker placeholder="请选择月份" v-model="addForm.date" style="width: 240px" />
        </a-form-model-item>
        <a-form-model-item
          :rules="{
            required: true,
            message: '请选择'
          }"
          ref="companyInfoList"
          label="选择用工单位"
          prop="companyInfoList"
        >
          <a-tree-select
            v-model="addForm.companyInfoList"
            :tree-data="companyDataList"
            :filterTreeNode="false"
            :replaceFields="replaceFields2"
            labelInValue
            treeCheckable
            placeholder="请选择"
            style="width: 240px"
            @search="treeSearch"
          />
        </a-form-model-item>
        <a-form-model-item
          :rules="{
            required: true,
            message: '请选择'
          }"
          ref="type"
          label="明细表类型"
          prop="type"
        >
          <a-select placeholder="请选择" v-model="addForm.type" style="width: 240px">
            <a-select-option value="customer"> 客户明细表 </a-select-option>
            <a-select-option value="salary"> 薪资明细表 </a-select-option>
            <a-select-option value="social"> 社保明细表 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="addForm.type === 'customer' || addForm.type === 'salary'"
          :rules="{
            required: addForm.type === 'salary',
            message: '请选择'
          }"
          ref="date"
          label="薪资数据来源月份"
          prop="date"
        >
          <a-month-picker placeholder="请选择月份" v-model="addForm.salaryDate" style="width: 240px" />
        </a-form-model-item>
        <a-form-model-item
          v-if="addForm.type === 'customer' || addForm.type === 'social'"
          :rules="{
            required: addForm.type === 'social',
            message: '请选择'
          }"
          ref="date"
          label="社保数据来源月份"
          prop="date"
        >
          <a-month-picker placeholder="请选择月份" v-model="addForm.socialDate" style="width: 240px" />
        </a-form-model-item>
        <a-form-model-item
          v-if="addForm.type === 'customer'"
          :rules="{
            required: false,
            message: '请选择'
          }"
          ref="serviceChargeIds"
          label="服务费项"
          prop="serviceChargeIds"
        >
          <a-select
            v-model="addForm.serviceChargeIds"
            :options="fuwufeixiangLst"
            :filterOption="filterOption"
            mode="multiple"
            showSearch
            placeholder="请选择"
            style="width: 240px"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-spin>
</template>

<script>
import { findCompanyGroup } from "@/api/company/contract";
import { getCompanyReqNew, addCustomerReqNew, getDateReqNew, deleteItemReqNew } from "./api";
import TabGroup from "./group.vue";
import moment from "moment";
import _ from "lodash";

export default {
  components: { TabGroup },
  data() {
    return {
      groupType: "company",
      addForm: {},
      loading: false,
      companyDataList: [],
      date: null,
      customerDetailsType: undefined,
      companyName: "",
      addVisible: false,
      groupList: [],
      flatDataList: [],
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      typeDict: {
        customer: "客户明细表",
        social: "社保明细表",
        salary: "薪资明细表"
      },
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      fuwufeixiangLst: []
    };
  },
  computed: {},
  watch: {
    groupType(newVal) {
      if (newVal === "company") {
        this.getCompanyList();
      } else {
        this.$refs.tabGroup.loadData();
      }
    },
    customerDetailsType() {
      this.pagination.current = 1;
      this.getCompanyList();
    }
  },
  created() {
    this.getDate();
    this.loadFuwufeixiang();
  },
  methods: {
    onNameChange: _.throttle(function () {
      this.pagination.current = 1;
      this.getCompanyList();
    }, 1000),
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    loadFuwufeixiang() {
      this.$request({
        url: `/salary/api/v1/serviceCharges/selectByNameLike`
      })
        .then((res) => {
          this.fuwufeixiangLst = res.data.map((item) => ({
            value: item.id,
            label: item.name
          }));
        })
        .catch(() => {});
    },
    onCancel() {
      this.addVisible = false;
    },
    onShowSizeChange(current, pageSize) {
      this.pagination.current = current;
      this.pagination.pageSize = pageSize;
      this.getCompanyList();
    },
    formatYM(yl, ml) {
      if (yl) {
        return `${yl}-${ml < 10 ? "0" : ""}${ml}`;
      }
      return "--";
    },
    deleteItem(e) {
      deleteItemReqNew(e.customerDetailsIds[0])
        .then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "删除成功"
          });
          this.getDate();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    getDate() {
      getDateReqNew().then((res) => {
        if (this.$route.query.date) {
          this.date = moment(this.$route.query.date, "YYYY-MM");
        } else if (res.data && res.data.yearly && res.data.monthly) {
          this.date = moment(`${res.data.yearly}` + "-" + `${res.data.monthly}`, "YYYY-MM");
        } else {
          this.date = moment(moment().format("YYYY-MM"), "YYYY-MM");
        }
        this.findCompanyGroup();
        this.getCompanyList();
      });
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    showAdd() {
      this.addVisible = true;
      this.addForm = {};
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.companyDataList = this.addTreeSlot(res.data);
          this.flatten(this.companyDataList);
          this.addForm.companyInfoList = this.addForm.companyInfoList
            ? JSON.parse(JSON.stringify(this.addForm.companyInfoList))
            : undefined;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.flatDataList.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    handleAddOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var companyArr = [];
          this.addForm.companyInfoList.forEach((item) => {
            this.flatDataList.forEach((item2, index2) => {
              if (item2.uuid && item2.uuid === item.value) {
                companyArr.push({ companyId: item2.id, companyName: item2.name });
              }
            });
          });
          addCustomerReqNew({
            monthly: moment(this.addForm.date).format("MM"),
            type: this.addForm.type,
            yearly: moment(this.addForm.date).format("YYYY"),
            salaryMonthly: this.addForm.salaryDate ? moment(this.addForm.salaryDate).format("MM") : undefined,
            salaryYearly: this.addForm.salaryDate ? moment(this.addForm.salaryDate).format("YYYY") : undefined,
            socialMonthly: this.addForm.socialDate ? moment(this.addForm.socialDate).format("MM") : undefined,
            socialYearly: this.addForm.socialDate ? moment(this.addForm.socialDate).format("YYYY") : undefined,
            companyInfoList: companyArr,
            serviceChargeIds: this.addForm.serviceChargeIds || []
          }).then((res) => {
            this.addVisible = false;
            this.getCompanyList();
          });
        }
      });
    },
    goDetail(item) {
      localStorage.setItem("kehumingxibiao_item", JSON.stringify(item));
      this.$router.push({
        path: "kehumingxibiao/customerDetail",
        query: {
          monthly: moment(this.date).format("MM"),
          yearly: moment(this.date).format("YYYY"),
          formType: item.customerDetailsType,
          groupType: item.subjectType
        }
      });
    },
    getCompanyList() {
      this.loading = true;
      this.groupList = [];
      const params = {
        monthly: moment(this.date).format("MM"),
        yearly: moment(this.date).format("YYYY"),
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.customerDetailsType) {
        params["customerDetailsType"] = this.customerDetailsType;
      }
      if (this.companyName) {
        params["companyName"] = this.companyName;
      }
      getCompanyReqNew(params)
        .then((res) => {
          this.groupList = res.data.entities;
          this.pagination.total = res.data.entityCount;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log("debug log --> ", err);
        });
    },
    // 月份选择变化
    onMonthChange(e) {
      this.date = e;
      const query = JSON.parse(JSON.stringify(this.$router.history.current.query)); // 取当前路由query值并且深拷贝
      const path = this.$router.history.current.path; // 取当前路由地址
      query.date = moment(this.date).format("YYYY-MM"); // 修改变动的query值
      this.$router.push({ path, query }); // 改变query值
      this.pagination.current = 1;
      this.getCompanyList();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .ant-select-selection--multiple {
  max-height: 400px;
  overflow-y: auto;
}

.noShowIcon {
  width: 32px;
  height: 32px;
  background: var(--primary);
  border-radius: 8px;
  margin-right: 12px;
  color: #ffffff;
  line-height: 32px;
  text-align: center;
  box-shadow: 0px 2px 8px 1px var(--primary);
  flex-shrink: 0;
}
</style>
